package com.czk.jvm;

import java.lang.management.GarbageCollectorMXBean;
import java.lang.management.ManagementFactory;
import java.lang.management.MemoryMXBean;
import java.lang.management.MemoryUsage;
import java.util.Arrays;
import java.util.List;

/**
 * @Author:ChenZhangKun
 * @Date: 2021/8/9 9:49
 */
public class JvmStack {
    private static final long MB = 1048576L;

    public static void printMemoryInfo() {
        // 拿到内存管理对象
        MemoryMXBean memoryMXBean = ManagementFactory.getMemoryMXBean();
        // 拿到堆内存管理对象
        MemoryUsage heapMemoryUsage = memoryMXBean.getHeapMemoryUsage();
        //
        String info = String.format("\ninit: %s\t max: %s\t used: %s\t committed: %s\t use rate: %s\n",
                // 初始堆内存
                heapMemoryUsage.getInit() / MB + "MB",
                // 最大堆内存
                heapMemoryUsage.getMax() / MB + "MB",
                // 使用的堆内存
                heapMemoryUsage.getUsed() / MB + "MB",
                //
                heapMemoryUsage.getCommitted() / MB + "MB",
                // 使用比例
                heapMemoryUsage.getUsed() * 100 / heapMemoryUsage.getCommitted() + "MB" + "%");
        // 输出
        System.out.println(info);
        MemoryUsage nonheadMemory = memoryMXBean.getNonHeapMemoryUsage();
        info = String.format("init: %s\t max: %s\t used: %s\t committed: %s\t use rate: %s\n",
                nonheadMemory.getInit() / MB + "MB",
                nonheadMemory.getMax() / MB + "MB", nonheadMemory.getUsed() / MB + "MB",
                nonheadMemory.getCommitted() / MB + "MB",
                nonheadMemory.getUsed() * 100 / nonheadMemory.getCommitted() + "%"

        );
        System.out.println(info);
    }

    public static void printGcInfo() {
        List<GarbageCollectorMXBean> garbageCollectorMXBeans = ManagementFactory.getGarbageCollectorMXBeans();
        for (GarbageCollectorMXBean garbageCollectorMXBean : garbageCollectorMXBeans) {
            String info = String.format("name: %s\t count:%s\t took:%s\t pool name:%s",
                    garbageCollectorMXBean.getName(),
                    garbageCollectorMXBean.getCollectionCount(),
                    garbageCollectorMXBean.getCollectionTime(),
                    Arrays.deepToString(garbageCollectorMXBean.getMemoryPoolNames()));
            System.out.println(info);
        }
    }
}
